import { types, flow, applySnapshot } from 'mobx-state-tree';
import { Toast } from 'antd-mobile';
import { history } from './RouterAndHistory';

function sleep() {
  return new Promise(r => setTimeout(r, 500));
}

const SessionModel = types.model('SessionModel', {
  userId: '',
}).actions(self => {
  return {
    login: flow(function* (userId: string) {
      yield sleep();
      self.userId = userId;
      // navigate to from page
      Toast.show({ content: '登录成功!即将返回之前的页面' });
      history.goBack();
    }),
    logout: flow(function* () {
      yield sleep();
      applySnapshot(self, { userId: '' }); // 完全清除遗留信息
      // navigate to /
      Toast.show({ content: '注销成功!即将返回网站首页' });
      history.push('/');
    }),
  };
});

export const session = SessionModel.create();
